package org.apache.servicecomb.samples.practise.houserush.gateway.dispatcher.filter;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.servicecomb.common.rest.codec.RestObjectMapperFactory;
import org.apache.servicecomb.common.rest.codec.produce.ProduceProcessor;

import javax.ws.rs.core.MediaType;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;

public class ProduceJsonProcessor implements ProduceProcessor {
    private ObjectMapper mapper = new ObjectMapper();

    public ProduceJsonProcessor() {

        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        mapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
        mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

        //解决时间格式转换的问题
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mapper.setDateFormat(format);

        //数据为空的处理
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    @Override
    public String getName() {
        return MediaType.APPLICATION_JSON;
    }

    @Override
    public void doEncodeResponse(OutputStream output, Object result) throws Exception {
        mapper.writeValue(output, result);
    }

    @Override
    public Object doDecodeResponse(InputStream input, JavaType type) throws Exception {
        return mapper.readValue(input, type);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
